# -*- coding: utf-8 -*-
from rest_framework import serializers
from user.models import User,Role,UserRole
from rest_framework_jwt.settings import api_settings


class UserSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='username',required=False)
    is_superuser = serializers.CharField(default=0)
    roles = serializers.SerializerMethodField(required=False)

    class Meta:
        model = User              # 具体对哪个表进行序列化
        fields = '__all__'        # 所有字段
        read_only_fields = ('id',)
        extra_kwargs = {
            "password": {
                "min_length": 6,          # 给地址增加 最小长度限制
                "default": '123456',      # 增加默认值
            },
            "email": {
                "required":True,
            },
            "mobile": {
                "required": True,
            },
        }

    def get_roles(self,row):
        # row == User
        roles_json = UserRole.objects.filter(user=row).values('role__id','role__name')
        return list(roles_json)

    def create(self, data):
        print(data, '99999999999999')
        username = data.get('username','')
        password = data.get('password','')
        mobile = data.get('mobile','')
        email = data.get('email','')
        user = User(username=username, email=email,mobile=mobile)
        user.set_password(password)                   # 密码加密
        user.save()

        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user

    def update(self, instance, validated_data):
        instance.mobile = validated_data.get('mobile')
        instance.email = validated_data.get('email')
        instance.save()
        return instance


class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Role
        fields = '__all__'